import React from 'react';
import { Card, List, Image, Form, Input, Select, Button, Space, Modal, Upload, Carousel, message, Tag } from 'antd';
import { PlusOutlined, DeleteOutlined, EyeOutlined, UploadOutlined } from '@ant-design/icons';

const { Option } = Select;

// 将文件转为 base64 以便本地预览与存储
const getBase64 = (file) => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => resolve(reader.result);
  reader.onerror = (error) => reject(error);
});

export default function Certificate() {
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [preview, setPreview] = React.useState({ open: false, img: '' });
  const [addOpen, setAddOpen] = React.useState(false);
  const [list, setList] = React.useState(() => {
    const saved = localStorage.getItem('cert-list');
    if (saved) return JSON.parse(saved);
    // 初始模拟数据
    return Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      name: `示例凭证-${i + 1}`,
      type: i % 3 === 0 ? 'SSL' : i % 3 === 1 ? 'License' : 'Auth',
      desc: '用于演示的本地凭证条目',
      img: `https://placehold.co/300x180/png?text=Certificate+${i + 1}`,
      createTime: new Date(Date.now() - i * 86400000).toLocaleString(),
    }));
  });
  const [filtered, setFiltered] = React.useState(list);

  React.useEffect(() => {
    localStorage.setItem('cert-list', JSON.stringify(list));
    handleSearch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [list]);

  const handleSearch = () => {
    const { name, type } = form.getFieldsValue();
    const res = list.filter((item) => {
      const matchName = name ? item.name.toLowerCase().includes(name.toLowerCase()) : true;
      const matchType = type ? item.type === type : true;
      return matchName && matchType;
    });
    setFiltered(res);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(list);
  };

  const openPreview = (img) => setPreview({ open: true, img });

  const deleteItem = (id) => {
    setList((prev) => prev.filter((x) => x.id !== id));
    message.success('已删除该凭证');
  };

  const deleteAll = () => {
    Modal.confirm({
      title: '清空确认',
      content: '确定要删除全部凭证吗？此操作不可恢复。',
      onOk: () => {
        setList([]);
        message.success('已清空所有凭证');
      },
    });
  };

  const onAddSubmit = async () => {
    try {
      const values = await addForm.validateFields();
      const id = Date.now();
      const item = {
        id,
        name: values.name,
        type: values.type,
        desc: values.desc || '',
        img: values.img,
        createTime: new Date().toLocaleString(),
      };
      setList((prev) => [item, ...prev]);
      setAddOpen(false);
      addForm.resetFields();
      message.success('新增凭证成功（本地保存）');
    } catch (e) {}
  };

  const uploadProps = {
    maxCount: 1,
    accept: 'image/*',
    beforeUpload: async (file) => {
      const base64 = await getBase64(file);
      addForm.setFieldsValue({ img: base64 });
      message.success('图片已读取并预览');
      return false; // 阻止真实上传
    },
    showUploadList: false,
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title="凭证管理" extra={<Space>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddOpen(true)}>新增凭证</Button>
        <Button danger icon={<DeleteOutlined />} onClick={deleteAll}>清空全部</Button>
      </Space>} variant="outlined">
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ rowGap: 12 }}>
          <Form.Item label="名称" name="name">
            <Input allowClear placeholder="输入名称关键词" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item label="类型" name="type">
            <Select allowClear placeholder="请选择类型" style={{ width: 180 }}>
              <Option value="SSL">SSL</Option>
              <Option value="License">License</Option>
              <Option value="Auth">Auth</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={onReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {filtered.length > 0 && (
        <Card title="预览轮播" variant="outlined">
          <Carousel autoplay dots>
            {filtered.slice(0, 8).map((item) => (
              <div key={item.id} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Image src={item.img} alt={item.name} width={500} height={300} style={{ objectFit: 'contain' }} />
              </div>
            ))}
          </Carousel>
        </Card>
      )}

      <Card title={`凭证列表（共 ${filtered.length} 条）`} variant="outlined">
        <List
          grid={{ gutter: 16, column: 3 }}
          dataSource={filtered}
          loading={loading}
          pagination={{ pageSize: 6 }}
          renderItem={(item) => (
            <List.Item key={item.id}>
              <Card
                cover={<Image src={item.img} alt={item.name} height={180} style={{ objectFit: 'cover' }} />}
                actions={[
                  <Space key="preview" onClick={() => openPreview(item.img)}><EyeOutlined /> 预览</Space>,
                  <Space key="delete" onClick={() => deleteItem(item.id)} style={{ color: 'red' }}><DeleteOutlined /> 删除</Space>,
                ]}
                variant="outlined"
              >
                <Card.Meta title={item.name} description={(
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div>{item.desc}</div>
                    <Space>
                      <Tag color="blue">类型：{item.type}</Tag>
                      <Tag>时间：{item.createTime}</Tag>
                    </Space>
                  </div>
                )} />
              </Card>
            </List.Item>
          )}
        />
      </Card>

      <Modal open={preview.open} title="图片预览" footer={null} onCancel={() => setPreview({ open: false, img: '' })}>
        {preview.img && (<Image src={preview.img} alt="预览" width="100%" />)}
      </Modal>

      <Modal
        open={addOpen}
        title="新增凭证"
        okText="保存"
        cancelText="取消"
        onOk={onAddSubmit}
        onCancel={() => setAddOpen(false)}
      >
        <Form form={addForm} layout="vertical" initialValues={{ type: 'SSL' }}>
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="例如：证书-2025-10" />
          </Form.Item>
          <Form.Item label="类型" name="type" rules={[{ required: true, message: '请选择类型' }]}>
            <Select>
              <Option value="SSL">SSL</Option>
              <Option value="License">License</Option>
              <Option value="Auth">Auth</Option>
            </Select>
          </Form.Item>
          <Form.Item label="描述" name="desc">
            <Input.TextArea rows={3} placeholder="可选，描述此凭证用途" />
          </Form.Item>
          <Form.Item label="图片" required>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>选择图片（不上传）</Button>
              </Upload>
              <Form.Item name="img" noStyle rules={[{ required: true, message: '请先选择图片' }]}>
                <Input type="hidden" />
              </Form.Item>
              {addForm.getFieldValue('img') && (
                <Image src={addForm.getFieldValue('img')} alt="预览" width={240} />
              )}
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}